package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.先对手机号码进行判断，看看是否符合手机号码规范
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.不符合，返回一个错误信息
            return Result.fail("手机号码不正确");
        }
        //3.符合验证，生成一个验证码
        String code = RandomUtil.randomNumbers(6);
        //4.将验证码存入redis里面
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone, code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5.发送验证码
        log.info("发送验证码:{}",code);
        return Result.ok();
    }

    /**
     * 登录功能
     * @param loginForm
     * @param session
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //1.验证手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.不符合，返回一个错误信息
           return Result.fail("手机号码不正确");
        }
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        //3.验证验证码
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            return Result.fail("验证码错误");
        }
        //5.一致，根据手机号码查询用户，如果查询结果为null，那么就自动注册账号
        User user = query().eq("phone", loginForm.getPhone()).one();
        if (user == null) {
            //6.如果查询账号为空，就自动注册账号
            user = createUserWithPhone(phone);
        }

        //7.保存用户信息到redis里面
        //7.1随机生成token作为登录id
        String token = UUID.randomUUID().toString(true);
        //7.2将user对象转为hash对象进行存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> usermap = BeanUtil.beanToMap(userDTO);
        usermap.forEach((k, v) -> {
            if (v instanceof Long) {
                usermap.put(k, v.toString());
            }
        });
        //7.3存储
        String tokenKey = LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,usermap);
        //7.4设置token有效期
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //返回token
        return Result.ok(token);
    }

    /**
     * 实现签到功能
     */
    @Override
    public void sign() {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.获取当前日期
        LocalDate localDate = LocalDate.now();
        //3.进行日期转换
        String format = localDate.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //4.进行key值拼接
        String key = SIGN_KEY + userId +format;
        //5.查询当前日期是这个月的第几天
        int dayOfMonth = localDate.getDayOfMonth();
        //6.将日期存储进redis
        Boolean b = stringRedisTemplate.opsForValue().setBit(key, dayOfMonth, true);
        if (!b) {
            throw new RuntimeException("签到失败！");
        }
    }

    /**
     * 连续签到统计
     * @return
     */
    @Override
    public Object signCount() {
        //1.获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //2.获取当前日期
        LocalDate localDate = LocalDate.now();
        String format = localDate.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = localDate.getDayOfMonth();

        String key = SIGN_KEY + userId +format;
        //3.获取连续签到的redis数据
        List<Long> list = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().
                get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));

        //4.进行非空判断
        if (list == null || list.isEmpty()){
            return Result.ok(0);
        }
        //5.获取签到数据
        Long days = list.get(0);
        int count = 0;
        while (true){
            if ((days & 1) == 0) {
                break;
            }else {
                count++;
            }
            days >>>= 1;
        }
        return Result.ok(count);
    }

    //自动创建用户
    private User createUserWithPhone(String phone) {
        //1.创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        //2.保存用户
        save(user);
        return user;
    }
}
